package com.example.sunflowers.viewmodels

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import cn.trans88.taxiappkotlin.ext.loge
import com.example.sunflowers.BuildConfig
import com.example.sunflowers.data.db.Plant
import com.example.sunflowers.data.repository.GardenPlantingRepository
import com.example.sunflowers.data.repository.PlantRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 *
 * @Author： LJH
 * @Time： 2024/1/30
 * @description：
 */
@HiltViewModel
class PlantDetailViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    val plantRepository: PlantRepository,
    private val gardenPlantingRepository: GardenPlantingRepository
) :ViewModel(){

    companion object{
        private const val PLANT_ID_STATE_KEY = "plantId"
    }

    val plantId:String = savedStateHandle.get<String>(PLANT_ID_STATE_KEY)!!

    val isPlanted = gardenPlantingRepository.isPlanted(plantId).asLiveData()
    val plant = MutableLiveData<Plant>()


    fun addPlantToGarden(){
        viewModelScope.launch {
            gardenPlantingRepository.createGardenPlanting(plantId)
        }
    }

    fun hasValidUnsplashKey():Boolean{
        return BuildConfig.UNSPLASH_ACCESS_KEY != "null"
    }

    fun refreshPlant() = viewModelScope.launch {
        val plantById = plantRepository.getPlant(plantId)
        plant.setValue(plantById)
    }
}